const express = require('express')
const { nanoid } = require('nanoid')
const { getUserInfo } = require('../utils/permission')
const User = require('../models/User')
const router = express.Router()
const CryptoJS = require('crypto-js')

/**
 * 根据 token 获取用户信息
 */
router.get('/self', (req, res) => {
  const { phone } = getUserInfo(req)
  User
    .findOne({ phone }, { _id: false, code: false, password: false, code: false, token: false, cart: false, orders: false, addresses: false, __v: false })
    .then(user => {
      if (user) {
        res.json({
          code: 200,
          data: {
            userInfo: user,
            message: '获取成功'
          },
          message: ''
        })
      } else {
        res.json({
          code: 200,
          data: {
            userInfo: null,
            message: '用户未登录!'
          }
        })
      }
    })
})

/**
 * 检测手机号是否被占用
 */
router.get('/:phone', (req, res) => {
  const { phone } = req.params
  User
    .find({phone})
    .then(data => {
      if (data.length) {
        res.json({
          code: 200,
          data: {
            status: 200,
            message: '该手机号已注册'
          },
          message: ''
        })
      } else {
        res.json({
          code: 200,
          data: {
            status: 404,
            message: '该手机号未被注册'
          },
          message: ''
        })
      }
    })
})

/**
 * 获取验证码
 */
router.get('/:phone/code', (req, res) => {
  const { phone } = req.params
  const code = Math.random().toString().slice(2).slice(-4).padStart(4, '0')
  User
    .find({ phone }, {__v: false})
    .then(data => {
      if (data.length) {
        // 有用户，保存验证码到数据库
        User
          .updateOne({phone}, {code})
          .then(() => {
            res.json({
              code: 200,
              data: {
                code
              }
            })
          })
      } else {
        // 没有用户，创建新用户，并保存验证码到数据库
        new User({phone, code, avatarUrl: 'https://joeschmoe.io/api/v1/random', scores: 999, nickname: '白丁用户', status: -1})
          .save()
          .then(() => {
            res.json({
              code: 200,
              data: {
                code
              }
            })
          })
      }
    })
})

/**
 * 验证码校验
 */
router.get('/:phone/verifycode', (req, res) => {
  const { phone } = req.params
  const { code } = req.query
  User
    .find({ phone, code }, {__v: false})
    .then(data => {
      if (data.length) {
        res.json({
          code: 200,
          data: {
            status: 200,
            message: '校验成功'
          },
          message: ''
        })
      } else {
         res.json({
          code: 200,
          data: {
            status: 404,
            message: '验证码校验失败'
          }
         })
      }
    })
})

/**
 * 用户注册
 */
router.post('/register', (req, res) => {
  const { phone, password } = req.body

  User
    .find({ phone })
    .then(data => {
      if (data.length === 1) {
        const { status } = data[0]
        if (status === -1) {
          User
            .updateOne({phone}, {password: CryptoJS.MD5(password).toString(), code: '', status: 1})
            .then(() => {
              res.json({
                code: 200,
                data: {
                  status: 200,
                  message: '用户注册成功'
                },
                message: ''
              })
            })
        } else {
          res.json({
            code: 200,
            data: {
              status: 500,
              message: '用户已存在, 请不要重复注册'
            },
            message: '',
          })
        }
      } else {
        res.json({
          code: 200,
          data: {
            status: 404,
            message: '请先校验验证码再注册'
          },
          message: '',
        })
      }
    })
})

/**
 * 绑定用户名
 */
router.put('/bindusername', (req, res) => {
  const { phone } = getUserInfo(req)
  const { username } = req.body

  User
    .find({ username })
    .then(users => {
      if (users.length) {
        const user = users[0]
        if (user.phone !== phone) {
          res.json({
            code: 200,
            data: {
              status: 502,
              message: '用户名已被占用'
            },
            message: ''
          })
        } else {
          res.json({
            code: 200,
            data: {
              status: 200,
              message: '用户名绑定成功'
            },
            message: ''
          })
        }
      } else {
        User
          .find({ phone })
          .then(data => {
            if (data.length === 1) {
              User
                .updateOne({phone}, { username })
                .then(() => {
                  res.json({
                    code: 200,
                    data: {
                      status: 200,
                      message: '用户名绑定成功'
                    },
                    message: ''
                  })
                })
            } else {
              res.json({
                code: 200,
                data: {
                  status: 500,
                  message: '未找到注册用户信息,绑定失败'
                },
                message: '',
              })
            }
          })
      }
    })
})

/**
 * 修改密码
 */
router.put('/modifypassword', (req, res) => {
  const { phone } = getUserInfo(req)
  const { oldPassword, newPassword } = req.body
  User
    .findOneAndUpdate(
      { phone, password: CryptoJS.MD5(oldPassword).toString()},
      { password: CryptoJS.MD5(newPassword).toString() },
    )
    .then(user => {
      if (user) {
        res.json({
          code: 200,
          data: {
            status: 200,
            message: '密码修改成功'
          },
          message: ''
        })
      } else {
        res.json({
          code: 200,
          data: {
            status: 404,
            message: '旧密码有误'
          },
          message: ''
        })
      }
    })
})


// ////////// TODO..............

// /**
//  * 根据 token 获取用户的基本信息
//  */
// router.get('/', (req, res) => {
//   const user = getUserInfo(req)
//   User
//     .find({phone: user?.phone})
//     .then(data => {
//       const orders = data[0]?.orders ?? []
//       res.json({
//         code: 200,
//         data: {
//           orders
//         }
//       })
//     })
// })

// /**
//  * 添加订单信息
//  */
// router.post('/', (req, res) => {
//   const user = getUserInfo(req)
//   if (user) {
//     /* 从请求中获取添加的订单数据 */
//     const { order } = req.body

//     User
//       .find({phone: user?.phone}, 'orders')
//       .then(data => {
//         const orders = data[0]?.orders ?? []
//         order.id = nanoid() // 订单号
//         orders.push(order)
//         User
//           .updateOne({phone: user.phone}, {orders})
//           .then(() => {
//             res.json({
//               code: 200,
//               data: {
//                 status: 200,
//                 message: '添加成功'
//               }
//             })
//           })
//       })
//   } else {
//     res.json({
//       code: 200,
//       data: {
//         status: 400,
//         message: '没有用户信息'
//       }
//     })
//   }
// })

// /**
//  * 修改订单信息
//  */
// router.put('/:id', (req, res) => {
//   const user = getUserInfo(req)
//   if (user) {
//     const { id } = req.params
//     const { order } = req.body
    
//     User
//       .find({phone: user?.phone}, 'orders')
//       .then(data => {
//         const orders = data[0]?.orders ?? []

//         const result = orders.map(orderItem => {
//           const copy = { ...orderItem }
//           if (copy.id === id) {
//             return {id, ...order}
//           }
//           return copy
//         })

//         User
//           .updateOne({phone: user.phone}, { orders: result })
//           .then(() => {
//             res.json({
//               code: 200,
//               data: {
//                 status: 200,
//                 message: '更新成功'
//               }
//             })
//           })
//       })
//   } else {
//     res.json({
//       code: 200,
//       data: {
//         message: '没有用户信息'
//       }
//     })
//   }
// })

// /**
//  * 删除订单
//  */
// router.delete('/:id', (req, res) => {
//   const user = getUserInfo(req)
//   if (user) {
//     const { id } = req.params
    
//     User
//       .find({phone: user?.phone}, 'orders')
//       .then(data => {
//         const orders = data[0]?.orders ?? []

//         const result = orders.filter(orderItem => orderItem.id !== id)

//         User
//           .updateOne({phone: user.phone}, { orders: result })
//           .then(() => {
//             res.json({
//               code: 200,
//               data: {
//                 status: 200,
//                 message: '删除成功'
//               }
//             })
//           })
//       })
//   } else {
//     res.json({
//       code: 200,
//       data: {
//         message: '没有用户信息'
//       }
//     })
//   }
// })

module.exports = router
